package com.weigee.ktv.presenter.adapter.rv

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.linde.library.adapter.BaseRvAdapter
import com.linde.library.adapter.SimpleViewHolder
import com.linde.library.util.DecimalPointUtil
import com.weigee.ktv.R
import com.weigee.ktv.model.entities.ShoppingGoodsEntity
import com.weigee.ktv.model.enums.ImagePreLoad
import com.weigee.ktv.model.enums.WeigeeHost
import com.weigee.ktv.model.interfaces.IShoppingCart
import kotlinx.android.synthetic.main.adapter_supermarket_shopping_list.view.*

/**
 * Created by linde on 2017/5/28.
 *<p/>
 */
class SupermarketShoppingListAdapter(val cart: IShoppingCart) : BaseRvAdapter<ShoppingGoodsEntity>()
{
    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): SimpleViewHolder
    {
        val view = LayoutInflater.from(parent?.context).inflate(R.layout.adapter_supermarket_shopping_list, parent, false)
        return SimpleViewHolder(view)
    }

    override fun onBindViewHolder(holder: SimpleViewHolder?, position: Int)
    {
        holder ?: return
        val v = holder.itemView
        val entity = mDataList[position]
        // 加载图片
        Glide.with(v.context).load(WeigeeHost.TEST_IMAGE_HEADER.url + entity.img).placeholder(ImagePreLoad.IMAGE.res).into(v.iv_shopping_goods_logo)
        Glide.with(v.context).load(WeigeeHost.TEST_IMAGE.url).asBitmap().placeholder(ImagePreLoad.IMAGE.res).into(v.iv_add_to_cart)
        Glide.with(v.context).load(WeigeeHost.TEST_IMAGE.url).asBitmap().placeholder(ImagePreLoad.IMAGE.res).into(v.iv_sub_from_cart)
        // 商品参数
        v.tv_shopping_goods_name.text = entity.name
        v.tv_shopping_goods_brief.text = entity.description
        v.tv_prise.text = ("¥ " + DecimalPointUtil.point(0, entity.price))
        // 跑马灯
        v.tv_shopping_goods_name.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) v.requestFocus()
        }
        // 购物车参数
        val cartNum = cart.getShoppingCartNum(null, entity.categoryId, entity.id)
        if (cartNum > 0)
        {
            v.iv_sub_from_cart.visibility = View.VISIBLE
            v.tv_check_num.visibility = View.VISIBLE
            v.tv_check_num.text = cartNum.toString()
        }
        else
        {
            v.iv_sub_from_cart.visibility = View.GONE
            v.tv_check_num.visibility = View.GONE
        }
        v.iv_add_to_cart.setOnClickListener({
            cart.addToCart(null, entity)
        })
        v.iv_sub_from_cart.setOnClickListener({
            cart.removeFromCart(null, entity.categoryId, entity.id)
        })
    }
}